#include "communication-worker.h"

CommunicationWorker::CommunicationWorker(const string &uartDevice)
{
    devicemanager = new SmartDeviceManager(uartDevice);
    deviceMap["doorlock"] = new CommunicationDeviceDoorlock(devicemanager);
    deviceMap["electrical"] = new CommunicationDeviceElectrical(devicemanager);
    deviceMap["sensor"] = new CommunicationDeviceSensor(devicemanager);
    deviceMap["sniffing"] = new CommunicationDeviceSniffing(devicemanager);
    deviceMap["list"] = new CommunicationDeviceList();

    fingerPrintManger = new FingerprintManager(new FingerPrintDevice("/dev/ttyUSB0"));
    deviceMap["fingerprint"] = new CommunicationDeviceFingerPrint(fingerPrintManger);
}

void CommunicationWorker::dowork(const CommunicationMessage &message)
{
    vector<uint8_t> packet = message.getPacket();
    NetCommunication *netObj = message.getNetCommunicationObject();
    // vector 转json udp 他们发的json字符串哟
    string jsonData(packet.data(), packet.data() + packet.size());
    cout << "----接收到的json字符串---" << endl;
    cout << jsonData << endl;

    SmartDeviceNetProtocol protocol = SmartDeviceNetProtocol::fromJsonData(jsonData);
    if (protocol.empty())
    {
        fprintf(stderr, "SmartDeviceNetProtocol obj is empty\n ");
        return;
    }
    string operation = protocol.getOperation();
    CommunicationDevice *device = deviceMap[operation];
    if (!device)
    {
        fprintf(stderr, "Invalid operation:%s \n ", operation.c_str());
        return;
    }
    device->communication(protocol, netObj);
}
